/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersect = function(nums1, nums2) {
  let count1 = [], count2 = [], result = [];
  for(let i = 0; i < nums1.length; i++) {
    if(!count1[nums1[i]]) {
      count1[nums1[i]] = 1;
    } else {
      count1[nums1[i]]++;
    }
  }
  for(let i = 0; i < nums2.length; i++) {
    if(!count2[nums2[i]]) {
      count2[nums2[i]] = 1;
    } else {
      count2[nums2[i]]++;
    }
  }
  let max = Math.max(count1.length, count2.length);
  for(let i = 0; i < max; i++) {
    if(!count1[i] || !count2[i])
      continue;
    else {
      let minCount = Math.min(count1[i], count2[i]);
      for(let j = 0; j < minCount; j++)
        result.push(i);
    }
  }
  return result;
};

let nums1 = [1,2,2,1], nums2 = [2,2];
console.log(intersect(nums1, nums2));
nums1 = [4,9,5], nums2 = [9,4,9,8,4];
console.log(intersect(nums1, nums2));

